import { createSlice, type PayloadAction } from "@reduxjs/toolkit"
import type { tabListState, tabState } from "./types"

const initialState: tabState = {
  isCollapse: false,
  tabList: [
    {
      path: "/",
      name: "home",
      label: "首页"
    }
  ],
  currentMenu: {} as tabListState
}

const tabSlice = createSlice({
  name: "tab",
  initialState,
  reducers: {
    collapseMenu: state => {
      state.isCollapse = !state.isCollapse
    },

    selectMenuList: (state, { payload: val }: PayloadAction<tabListState>) => {
      if (val.name !== 'home') {
        state.currentMenu = val
        const result = state.tabList.findIndex(item => item.name === val.name)
        if (result === -1) {
          state.tabList.push(val)
        }
      } else if (val.name === 'home' && state.tabList.length === 1) {
        state.currentMenu = {} as tabListState
      }
    },

    closeTab: (state, { payload: val }: PayloadAction<tabListState>) => {
      const res = state.tabList.findIndex(item => item.name === val.name)
      state.tabList.splice(res, 1)
    },

    setCurrentMenu: (state, { payload: val }: PayloadAction<tabListState>) => {
      if (val.name === 'home') {
        state.currentMenu = {} as tabListState
      } else {
        state.currentMenu = val
      }
    }
  }
})

export default tabSlice.reducer
export const { collapseMenu, selectMenuList, closeTab, setCurrentMenu } = tabSlice.actions
